import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Row, Col, Table, Button, message, Modal, Space } from 'antd'
import { VideoCameraOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import moment from 'moment'
import style from './VideoMeetingDetail.module.less'
import OperateModal from '@components/VideoMeetingDetail/OperateModal'
import UploadModal from '@components/VideoMeetingDetail/UploadModal'
import InfoModal from '@components/VideoMeetingDetail/InfoModal'
import { download } from '@js/downloadRename'
import { formatCaseDataLicense } from '@src/assets/js/tool'
const { confirm } = Modal
function getColumns () {
  return [
    {
      title: '序号',
      dataIndex: 'order',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '仲裁地位',
      dataIndex: 'type',
      key: 'type'
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile'
    },
    {
      title: '认证情况',
      dataIndex: 'certifyid',
      key: 'certifyid',
      render: (v) => {
        return v ? '已认证' : '未认证'
      }
    },
    {
      title: '是否已签名',
      dataIndex: 'signed_fileid',
      key: 'signed_fileid',
      render: (v) => {
        return v ? '已签名' : ''
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status'
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      render: (value, line) => {
        const d = this.state.meetingData
        if (!d.id || ['预约', '变更'].indexOf(d.status) === -1) {
          return null
        }
        return (
          <span className={style['operate-cell']}>
            <span onClick={() => this.modifyHandle(line)}>修改</span>
            <span onClick={() => this.confirm('您确定要删除该参会人员吗？', () => this.delRequest(line.id))}>删除</span>
          </span>
        )
      }
    }
  ]
}
class VideoMeetingDetail extends Component {
  state = {
    list: [],
    loading: false,
    visible: false,
    modifyData: {},
    meetingData: {},
    caseData: {},
    uploadVisible: false,
    infoVisible: false
  }

  // 获取时间区间
  getTimeRange (start, end) {
    if (!start && !end) {
      return '未开始'
    }
    let year = ''
    if (start) {
      start = moment(start * 1000)
      year = start.format('YYYY-MM-DD')
    }
    if (start && end) {
      end = moment(end * 1000)
      return `${year} ${start.format('HH:mm')}~${end.format('HH:mm')}`
    }
    if (end) {
      return ''
    }
    return `${year} ${start.format('HH:mm')}`
  }

  // 获取会议数据
  getMeetingData () {
    return this.$get(`/api/xapc/meeting/${this.props.meta.id}`)
      .then(res => {
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({
          meetingData: res.data
        })
      })
  }

  // 获取案件数据
  getCaseData () {
    const id = this.props.meta.caseid
    if (!id) {
      return Promise.resolve()
    }
    this.$get(`/api/xapc/case/${id}`)
      .then(res => {
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        formatCaseDataLicense(res.data)
        const d = res.data
        d.applicant_name = (d.applicants || []).filter(li => li.status).map(li => li.name).join()
        d.respondent_name = (d.respondents || []).filter(li => li.status).map(li => li.name).join()
        this.setState({
          caseData: res.data
        })
      })
  }

  // 获取基础数据
  getBaseData () {
    const hide = message.loading('加载中', 120)
    Promise.all([this.getMeetingData(), this.getCaseData()])
      .then(res => {
        hide()
      })
      .catch(() => hide())
  }

  // 获取参会人员列表
  getPerson () {
    this.setState({ loading: true })
    this.$get('/api/xapc/meetingParticipant', {
      meetingid: this.props.meta.id
    }).then(res => {
      this.setState({ loading: false })
      this.setState({
        list: res.data.map((li, i) => {
          li.order = i + 1
          return li
        })
      })
    }).catch(() => this.setState({ loading: false }))
  }

  // 添加新人员
  addHandle () {
    this.setState({
      visible: true,
      modifyData: {}
    })
  }

  // 修改人员
  modifyHandle (li) {
    this.setState({
      visible: true,
      modifyData: li
    })
  }

  // 提交修改
  changePerson (d) {
    const { id } = d
    let type = 'post'
    let url = '/api/xapc/meetingParticipant'
    delete d.id
    if (id) {
      url = url + '/' + id
      type = 'put'
    }
    const hide = message.loading('提交中', 120)
    this[`$${type}`](url, d)
      .then(res => {
        hide()
        if (res.status === -1) {
          return message.warning(res.message)
        }
        this.setState({
          visible: false,
          modifyData: {}
        })
        this.getPerson()
      }).catch(e => hide())
  }

  // 删除人员请求
  delRequest (id) {
    const hide = message.loading('删除中', 120)
    this.$delete(`/api/xapc/meetingParticipant/${id}`)
      .then(res => {
        hide()
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.getPerson()
      }).catch(e => { hide() })
  }

  // 获取笔录模板
  getTemplate () {
    const hide = message.loading('加载中', 120)
    this.$post(`/api/xapc/meeting/createMeetingTemp/${this.props.meta.id}`)
      .then(res => {
        hide()
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        if (res.data) {
          download(res.data.docx_path, '笔录模板.docx')
        } else {
          message.warning('笔录模板不存在')
        }
      }).catch(() => hide())
  }

  // 二次确认
  confirm (content, callback = () => {}) {
    confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content,
      onOk () {
        callback()
      },
      okText: '确定',
      cancelText: '取消'
    })
  }

  // 开始会议
  startMeeting () {
    this.updateMeeting({
      status: '会议开始',
      meeting_begin_datetime: Math.floor(moment() / 1000)
    })
  }

  // 结束会议
  endMeeting () {
    this.updateMeeting({
      status: '会议结束',
      meeting_end_datetime: Math.floor(moment() / 1000)
    })
  }

  // 完成会议
  completeMeeting () {
    this.updateMeeting({
      status: '完成'
    })
  }

  updateMeeting (data = {}, callback = () => {}) {
    const hide = message.loading('加载中', 120)
    this.$put(`/api/xapc/meeting/${this.props.meta.id}`, data).then(res => {
      hide()
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.getBaseData()
      callback()
    }).catch(() => hide())
  }

  // 显示上传笔录
  showUpload () {
    this.setState({
      uploadVisible: true
    })
  }

  // 上传笔录
  uploadRequest (id) {
    const hide = message.loading('加载中', 120)
    this.$put('/api/xapc/meeting/uploadTemp', {
      meetingid: this.state.meetingData.id,
      fileid: id
    }).then(res => {
      hide()
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({
        uploadVisible: false
      })
      this.getBaseData()
    }).catch(() => hide())
  }

  // 查看会议信息
  openMeetingInfo () {
    this.setState({
      infoVisible: true
    })
  }

  toVideo (d) {
    if (!d.chair_joinuri) {
      return message.warning('视频庭审地址不存在')
    }
    window.open(d.chair_joinuri, '_blank')
  }

  componentDidMount () {
    this.getBaseData()
    this.getPerson()
  }

  // 渲染笔录文件列表
  renderFileList () {
    const list = this.state.meetingData.meeting_file || []
    if (list.length === 0) {
      return null
    }
    return (
      <span className={style['file-list']}>
        <span className={style['file-list-label']}>已上传的笔录：</span>
        {
          list.map((li, i) => {
            return <a className={style.link} key={i} onClick={() => download(li.path, li.original_filename)}>{li.original_filename}</a>
          })
        }
      </span>
    )
  }

  renderBtns () {
    if (!this.state.meetingData.id) {
      return null
    }
    const files = this.state.meetingData.meeting_file || []
    const hasFile = files.length > 0
    const d = this.state.meetingData
    const s = d.status
    if (['预约', '变更'].indexOf(s) !== -1) {
      const m = '您确定要开始信息后，系统会初始化会议账号，并通知相关参会人员。（账号为WH+手机号，密码为WH+手机号后6位）是否确认会议信息？'
      return (
        <>
          <Button type='primary' ghost onClick={() => this.addHandle()}>新增参会人员</Button>
          <Button type='primary' onClick={() => this.confirm(m, () => this.startMeeting())}>确认会议人员信息</Button>
        </>
      )
    }
    if (['会议开始'].indexOf(s) !== -1) {
      return (
        <>
          <Button type='primary' onClick={() => this.confirm('您确定要结束会议吗？', () => this.endMeeting())}>结束会议</Button>
          <Button type='primary' ghost onClick={() => this.openMeetingInfo()}>会议信息</Button>
          <Button onClick={() => this.getTemplate()}>下载笔录模板</Button>
          <Button onClick={() => this.toVideo(d)}>进入视频庭审</Button>
        </>
      )
    }
    if (['会议结束'].indexOf(s) !== -1) {
      return (
        <>
          <Button type='primary' disabled={!hasFile} onClick={() => this.confirm('会议完成后将无法再签署笔录，您是否确定要完成会议', () => this.completeMeeting())}>完成会议</Button>
          <Button type='primary' ghost onClick={() => this.showUpload()}>上传笔录</Button>
          <Button onClick={() => this.getTemplate()}>下载笔录模板</Button>
        </>
      )
    }
  }

  // 渲染已签名文件
  renderSignFiles () {
    const list = this.state.meetingData.signed_file || []
    if (list.length === 0) {
      return null
    }
    return (
      <Col span={8}>
        <div className={style['basic-cell']}>
          <div className={style['basic-cell-label']}>已签名文件：</div>
          <div className={style['basic-cell-text']}>
            {
              list.map((li, i) => {
                const name = li.original_filename || li.filename
                return <a className={style.link} onClick={() => download(li.path, name)} key={i}>{name}</a>
              })
            }
          </div>
        </div>
      </Col>
    )
  }

  render () {
    const data = this.state.meetingData || {}
    const caseData = this.state.caseData || {}
    const columns = getColumns.call(this)
    return (
      <div className={style.container}>
        <OperateModal
          visible={this.state.visible}
          hearingroomid={data.hearingroomid}
          meetingid={data.id}
          caseid={data.caseid}
          data={this.state.modifyData}
          hide={() => this.setState({ visible: false, modifyData: {} })}
          onChange={d => this.changePerson(d)}
        />
        <UploadModal visible={this.state.uploadVisible} onChange={id => this.uploadRequest(id)} hide={() => this.setState({ uploadVisible: false })} />
        <InfoModal visible={this.state.infoVisible} data={this.state.meetingData} hide={() => this.setState({ infoVisible: false })} />
        <div className={style.header}>
          <div className={style.title}>
            <div className={style['title-icon']}>
              <VideoCameraOutlined />
            </div>
            <div className={style['title-text']}>
              <span>{caseData.caseno_desc}</span>
            </div>
          </div>
        </div>
        <div className={style['basic-info']}>
          <Row>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>申请人：</div>
                <div className={style['basic-cell-text']}>{caseData.applicant_name || '无'}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>被申请人：</div>
                <div className={style['basic-cell-text']}>{caseData.respondent_name || '无'}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>案件状态：</div>
                <div className={style['basic-cell-text']}>{caseData.status || '无'}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>案件程序：</div>
                <div className={style['basic-cell-text']}>{caseData.procedure || '无'}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>办案秘书：</div>
                <div className={style['basic-cell-text']}>{caseData.processer || '无'}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>约庭用途：</div>
                <div className={style['basic-cell-text']}>{data.use || '无'}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>开庭时间：</div>
                <div className={style['basic-cell-text']}>{this.getTimeRange(data.begin_datetime, data.end_datetime)}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>实际时间：</div>
                <div className={style['basic-cell-text']}>{this.getTimeRange(data.meeting_begin_datetime, data.meeting_end_datetime)}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>开庭状态：</div>
                <div className={style['basic-cell-text']}>{data.status}</div>
              </div>
            </Col>
            {this.renderSignFiles()}
          </Row>
        </div>

        <div className={style['btn-line']}>
          <Space>
            {this.renderBtns()}
            {this.renderFileList()}
          </Space>
        </div>

        <div className={style['table-container']}>
          <Table loading={this.state.loading} rowKey='order' columns={columns} dataSource={this.state.list} pagination={false} onChange={v => this.tableChange(v)} />
        </div>
      </div>
    )
  }
}
const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
  }
})

export default connect(mapState, mapDispatch)(VideoMeetingDetail)
